#!/bin/bash

source commonlib.sh
##------------------------------------------
# 从源码构建 kube-cross 镜像和 pause 镜像
# 准备:
1. go 二进制
2. docker/isula-build 二进制
3. 设置GOPATH
4. 拉取kubernetes, release 仓库
##------------------------------------------

# Global vars
##-------------------------------------------
k8s_repo=$GOPATH/src/k8s.io/kubernetes
release_repo=$GOPATH/src/k8s.io/release
cross_img_makefile=$release_repo/images/build/cross/Makefile
cross_img_dockerfile=$release_repo/images/build/cross/Dockerfile
cross_name="k8s.gcr.io/build-image/kube-cross"
cross_version=$(cat $k8s_repo/build/build-image/cross/VERSION)
cross_img="$cross_name:$cross_version"

if [ ! -d $k8s_repo ] || [ ! -d $release_repo ]; then
    log ERROR "k8s or release repo not exist"
fi

# Build kube-cross image
##-------------------------------------------
# get variables from Makefile
get_var() {
	input_file=$cross_img_makefile
	target_var=$1
	result=$(grep -E "^${target_var}" "${input_file}"| awk -F'=' '{print $2}')
	eval echo "${result}"
}


function build_kube_cross() {
    if [[ $(arch) == "x86_64" ]]; then
        target_platform="linux/amd64"
    else
        target_platform="linux/arm64"
    fi
    go_version=$(get_var GO_VERSION)
    protobuf_version=$(get_var PROTOBUF_VERSION)
    etcd_version=$(get_var ETCD_VERSION)
    image_name=$(get_var IMGNAME)
    image_version=$(get_var IMAGE_VERSION)

    cp /etc/resolv.conf .
    line_num=$(grep -n ^FROM $cross_img_dockerfile | awk -F":" '{print $1}')
    sed -i "${line_num}aCOPY ./resolv.conf /etc/reslov.conf" $cross_img_dockerfile

    # docker build --build-arg GO_VERSION="${go_version}" --build-arg TARGETPLATFORM="${target_platform}" --build-arg PROTOBUF_VERSION="${protobuf_version}" --build-arg ETCD_VERSION="${etcd_version}" -t "${image_name}":"${image_version}" -f   ${cross_img_dockerfile} .
    # docker tag ${image_name}:${image_version} $cross_img

    isula-build ctr-img build --build-arg GO_VERSION="${go_version}" \
        --build-arg TARGETPLATFORM="${target_platform}" \
        --build-arg PROTOBUF_VERSION="${protobuf_version}" \
        --build-arg ETCD_VERSION="${etcd_version}" \ 
        -t "${image_name}":"${image_version}" -f Dockerfile -o docker-daemon:$cross_img .
}

function build_pause() {
    cd $k8s_repo/build/pause
    make build
    if [[ $(arch) == "x86_64" ]]; then
        target_platform="amd64"
    else
        target_platform="arm64"
    fi
    pause_name="pause"
    pause_version="3.2"
    # docker build -t pause:${pause_version} --build-arg BASE=scratch --build-arg ARCH=${target_platform} .
    isula-build ctr-img build -f Dockerfile -t ${pause_name}:${pause_version} \
        --build-arg BASE=scratch \
        --build-arg ARCH=${target_platform} \
        -o docker-daemon:${pause_name}:${pause_version}
}

build_kube_cross
build_pause
